<?php

class Curl {
    
    const WEIXIN_DOMAIN = 'https://api.weixin.qq.com/';
    
    //get 请求
    public function is_getRequest($method){
        $res = ($method === 'get') ?  true : false;
        return $res;
    }
    
    //post 请求
    public function is_postRequest($method){
        $res = ($method === 'post') ? true : false;
        return $res;
    }
    
    // 执行 curl 请求
    public function request($api='', $method='post', $params=array()){
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //控制输出流
        
        if($this->is_getRequest($method)){            //执行 get 请求
            $params = http_build_query($params);
            $url = self::WEIXIN_DOMAIN . $api . '?' . $params;
            curl_setopt($ch, CURLOPT_URL, $url);
        }else if($this->is_postRequest($method)){     //执行 post 请求
            $url = self::WEIXIN_DOMAIN . $api;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        
        $output = curl_exec($ch);
        curl_close($ch);
        if($output === FALSE){
            return 'curl_request_error';
        }
        return $output;
    }
}




class Access_token {
    
    private $api = 'cgi-bin/token';
    private $appid = 'wx94f24e9dc5fcd30e';
    private $appsecret = '6da5410868473743de7b1cd6962f4b5c';
    
    public function getToken(){
        $param = array(
            'grant_type' => 'client_credential',
            'appid' => $this->appid,
            'secret' => $this->appsecret
        );
        
        $curl = new Curl();
        $res = $curl->request($this->api, 'get', $param);
        echo $res;
    }
}

$token = new Access_token();
$token->getToken();
